package bsi.vn.FirstApp;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import bsi.vn.Data.CookieData;
import bsi.vn.Lib.Consts;
import bsi.vn.Lib.ProcessFunc;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
//import android.animation.Animator;
//import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;

public class TicketDetailActivity extends Activity {
	private String Result = "";
	private int TicketId = 0;
	
	private View mTDFinish;
	private View mTDInformation;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_ticket_detail);
		
		mTDInformation = findViewById(R.id.tdllInformation);
		mTDFinish = findViewById(R.id.tdllFinish);
		
		//Departure button
		Button btDeparture = (Button)findViewById(R.id.tdbtDeparture);
		btDeparture.setOnClickListener(new OnClickListener() {  
        	@Override
			public void onClick(View v) { 
        		myUpdateAsyncTask myUpdateWebFetch = new myUpdateAsyncTask();
        		myUpdateWebFetch.execute(String.valueOf(Consts.SF_DEPARTURE), String.valueOf(R.id.tdtvDeparture), String.valueOf(R.id.tdetProcess), String.valueOf(R.id.tdbtDeparture));
           }
		});
        //end Departure button
		
		//Arrive button
		Button btArrive = (Button)findViewById(R.id.tdbtArrive);
		btArrive.setOnClickListener(new OnClickListener() {  
		      	@Override
				public void onClick(View v) { 
		      		myUpdateAsyncTask myUpdateWebFetch = new myUpdateAsyncTask();
		      		myUpdateWebFetch.execute(String.valueOf(Consts.SF_ARRIVE), String.valueOf(R.id.tdtvArrive), String.valueOf(R.id.tdetProcess), String.valueOf(R.id.tdbtArrive));
		        }
		});
		//end Arrive button
				
		//Process button
		Button btProcess = (Button)findViewById(R.id.tdbtProcess);
		btProcess.setOnClickListener(new OnClickListener() {  
		   	@Override
			public void onClick(View v) { 
		   		myUpdateAsyncTask myUpdateWebFetch = new myUpdateAsyncTask();
		   		myUpdateWebFetch.execute(String.valueOf(Consts.SF_PROCESS), String.valueOf(R.id.tdtvProcess), String.valueOf(R.id.tdetProcess), String.valueOf(R.id.tdbtProcess));
		   	}
		});
		//end Process button

		//Finish button
		Button btFinish = (Button)findViewById(R.id.tdbtFinish);
		btFinish.setOnClickListener(new OnClickListener() {  
		   	@Override
			public void onClick(View v) { 
		   		mTDInformation.setVisibility(View.INVISIBLE);
		   		mTDFinish.setVisibility(View.VISIBLE);
		   		//myUpdateAsyncTask myUpdateWebFetch = new myUpdateAsyncTask();
		   		//myUpdateWebFetch.execute(String.valueOf(Consts.SF_FINISH), String.valueOf(R.id.tdtvFinish), String.valueOf(R.id.tdetProcess), String.valueOf(R.id.tdbtFinish));
		   	}
		});
		//end Finish button
			
		//Finish button
		Button btReturn = (Button)findViewById(R.id.tdbtReturn);
		btReturn.setOnClickListener(new OnClickListener() {  
		   	@Override
			public void onClick(View v) { 
		   		myUpdateAsyncTask myUpdateWebFetch = new myUpdateAsyncTask();
		   		myUpdateWebFetch.execute(String.valueOf(Consts.SF_RETURN), String.valueOf(R.id.tdtvReturn), String.valueOf(R.id.tdetProcess));
		   	}
		});
		//end Finish button
		
		//Finish Cancel
		Button btCancel = (Button)findViewById(R.id.tdbtSubCancel);
		btCancel.setOnClickListener(new OnClickListener() {  
		  	@Override
			public void onClick(View v) { 
		   		mTDInformation.setVisibility(View.VISIBLE);
		   		mTDFinish.setVisibility(View.INVISIBLE);
		   		//myUpdateAsyncTask myUpdateWebFetch = new myUpdateAsyncTask();
		   		//myUpdateWebFetch.execute(String.valueOf(Consts.SF_FINISH), String.valueOf(R.id.tdtvFinish), String.valueOf(R.id.tdetProcess), String.valueOf(R.id.tdbtFinish));
		   	}
		});
		//end Cancel button
				
		//Finish Cancel
		Button btSubFinish = (Button)findViewById(R.id.tdbtSubFinish);
		btSubFinish.setOnClickListener(new OnClickListener() {  
		@Override
		public void onClick(View v) { 
			myUpdateAsyncTask myUpdateWebFetch = new myUpdateAsyncTask();
			myUpdateWebFetch.execute(String.valueOf(Consts.SF_FINISH), String.valueOf(R.id.tdtvFinish), String.valueOf(R.id.tdetProcess), String.valueOf(R.id.tdbtFinish));
			}
		});
		//end Cancel button
		
		TextView tvSerialNo = (TextView)findViewById(R.id.tdtvSerialNo);
		tvSerialNo.setOnClickListener(new OnClickListener() {  
			@Override
			public void onClick(View v) {
				TextView tvATMId = (TextView)findViewById(R.id.tdtvATMId);
				int ATMId = Integer.parseInt(tvATMId.getText().toString());
				Intent i = new Intent(getApplicationContext(), ATMDetailActivity.class);
				i.putExtra("ATMId", ATMId);
				startActivity(i);
				}
		});
				
        //Load data
		Bundle extras = getIntent().getExtras();
		if (extras == null) {
			return;
		}	
		TicketId = extras.getInt("TicketId");
		myAsyncTask myWebFetch = new myAsyncTask();
        myWebFetch.execute();
        //end Load data
  }
	
	private class myAsyncTask extends AsyncTask<String, String, String>    {
    	
    	@Override 	
		protected String doInBackground(String... params) {
			try {
		        Result = GetTicket();
		    } 
			catch (Exception e) {
				e.printStackTrace();
			}
			return Result;
		}
		
		@Override
		protected void onPostExecute(String result) {
			if (result == "")
			{
				Toast.makeText(TicketDetailActivity.this, "System error!", Toast.LENGTH_SHORT).show();
				return;
			}
			String sResponse[] = result.split("\\|");
			if (Integer.parseInt(sResponse[0]) != 0)
			{
				Toast.makeText(TicketDetailActivity.this, sResponse[1], Toast.LENGTH_SHORT).show();
				return;
			}
			try{
				JSONArray jArray = new JSONArray(sResponse[1]);
	        	JSONObject json_data = jArray.getJSONObject(0);
	        	
	        	TextView tvTicketNo = (TextView)findViewById(R.id.tdtvTicketNo);
				TextView tvType = (TextView)findViewById(R.id.tdtvType);
				TextView tvSerialNo = (TextView)findViewById(R.id.tdtvSerialNo);
				TextView tvAddress = (TextView)findViewById(R.id.tdtvAddress);
				TextView tvDesc = (TextView)findViewById(R.id.tdtvDesc);
				TextView tvDetail = (TextView)findViewById(R.id.tdtvDetail);
				TextView tvContact = (TextView)findViewById(R.id.tdtvContact);
				TextView tvPhone = (TextView)findViewById(R.id.tdtvPhone);
				TextView tvRequest = (TextView)findViewById(R.id.tdtvRequest);
				TextView tvAssign = (TextView)findViewById(R.id.tdtvAssign);
				TextView tvDeparture = (TextView)findViewById(R.id.tdtvDeparture);
				TextView tvArrive = (TextView)findViewById(R.id.tdtvArrive);
				TextView tvProcess = (TextView)findViewById(R.id.tdtvProcess);
				TextView tvFinish = (TextView)findViewById(R.id.tdtvFinish);
				TextView tvSubFinish = (TextView)findViewById(R.id.tdtvSubFinish);
				TextView tvReturn = (TextView)findViewById(R.id.tdtvReturn);
				TextView tvATMId = (TextView)findViewById(R.id.tdtvATMId);
				
				SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm");
				dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
				String formattedDate = dateFormat.format(new Date());
				
				String temp = json_data.getString(Consts.SDB_REQUEST).trim();
				if (temp.length() != 0)
					tvRequest.setText(dateFormat.format(ProcessFunc.stringToDate(temp, "ddMMyyyyHHmm")));
			
				temp = json_data.getString(Consts.SDB_ASSIGN).trim();
				if (temp.length() != 0)
					tvAssign.setText(dateFormat.format(ProcessFunc.stringToDate(temp, "ddMMyyyyHHmm")));
				
				temp = json_data.getString(Consts.SDB_DEPARTURE).trim();
				if (temp.length() == 0)
				{
					formattedDate = dateFormat.format(new Date());
					tvDeparture.setText(formattedDate);
				}
				else
				{
					tvDeparture.setText(dateFormat.format(ProcessFunc.stringToDate(temp, "ddMMyyyyHHmm")));
					Button btDeparture = (Button)findViewById(R.id.tdbtDeparture);
					btDeparture.setEnabled(false);
				}
			
				temp = json_data.getString(Consts.SDB_ARRIVE).trim();
				if (temp.length() == 0)
				{
					formattedDate = dateFormat.format(new Date());
					tvArrive.setText(formattedDate);
				}
				else
				{
					tvArrive.setText(dateFormat.format(ProcessFunc.stringToDate(temp, "ddMMyyyyHHmm")));
					Button btArrive = (Button)findViewById(R.id.tdbtArrive);
					btArrive.setEnabled(false);
				}
				
				temp = json_data.getString(Consts.SDB_PROCESS).trim();
				if (temp.length() == 0)
				{
					formattedDate = dateFormat.format(new Date());
					tvProcess.setText(formattedDate);
				}
				else
				{
					tvProcess.setText(dateFormat.format(ProcessFunc.stringToDate(temp, "ddMMyyyyHHmm")));
					Button btProcess = (Button)findViewById(R.id.tdbtProcess);
					btProcess.setEnabled(false);
				}
				
				temp = json_data.getString(Consts.SDB_FINISH).trim();
				if (temp.length() == 0)
				{
					formattedDate = dateFormat.format(new Date());
					tvFinish.setText(formattedDate);
					tvSubFinish.setText(formattedDate);
				}
				else
				{
					tvFinish.setText(dateFormat.format(ProcessFunc.stringToDate(temp, "ddMMyyyyHHmm")));
					Button btFinish = (Button)findViewById(R.id.tdbtFinish);
					btFinish.setEnabled(false);
				}
			
				temp = json_data.getString(Consts.SDB_RETURN).trim();
				if (temp.length() == 0)
				{
					formattedDate = dateFormat.format(new Date());
					tvReturn.setText(formattedDate);
				}
				else
				{
					tvReturn.setText(dateFormat.format(ProcessFunc.stringToDate(temp, "ddMMyyyyHHmm")));
					Button btReturn = (Button)findViewById(R.id.tdbtReturn);
					btReturn.setEnabled(false);
				}
				
				tvTicketNo.setText(json_data.getString(Consts.SDB_TICKETCODE));
				tvType.setText(json_data.getString(Consts.SDB_TYPE));
				tvATMId.setText(json_data.getString(Consts.SDB_ATMID));
				tvSerialNo.setText(json_data.getString(Consts.SDB_SERIALNO));
				tvAddress.setText(json_data.getString(Consts.SDB_ADDRESS));
				tvDesc.setText(json_data.getString(Consts.SDB_DESCRIPTION));
				tvDetail.setText(json_data.getString(Consts.SDB_DETAIL));
				tvContact.setText(json_data.getString(Consts.SDB_NAME));
				String sPhone = json_data.getString(Consts.SDB_PHONE);
				tvPhone.setText(Html.fromHtml("<a href=\"tel:"+ sPhone +"\">"+ sPhone +"</a>"));
				tvPhone.setMovementMethod(LinkMovementMethod.getInstance());
	       }
	        catch(JSONException e){
	        	Log.e("log_tag", "Error parsing data "+e.toString());
	        }
		}
		
        @Override
        protected void onPreExecute() {
        	//CheckDataValid();
			//showProgress(true);
            //super.onPreExecute();
            //tv.setText("Started Running….");
        }
        
        @Override
        protected void onProgressUpdate(String... text) {
         //finalResult.setText(text[0]);
         // Things to be done while execution of long running operation is in
         // progress. For example updating ProgessDialog
        }
 	}
	

	public class myUpdateAsyncTask extends AsyncTask<String, String, String>    {
    	
    	@Override 	
		protected String doInBackground(String...params) {
			try {
			    TextView tvTime = (TextView)findViewById(Integer.parseInt(params[1]));
			    EditText etProcess = (EditText)findViewById(Integer.parseInt(params[2]));
			    String dtData = tvTime.getText().toString();
			    Result = params[3] + "|";
			  if (params[0].length() == 0)
		        {
		        	Toast.makeText(TicketDetailActivity.this, "Search is Selected", Toast.LENGTH_SHORT).show();
		        	return "";
		        }
		        else
		        {
		        	dtData = dtData.replaceAll("/", "");
		        	dtData = dtData.replaceAll(" ", "");
		        	dtData = dtData.replaceAll(":", "");
		        	dtData = params[0] + "|" + dtData + "|" + etProcess.getText().toString();
		        	CookieData cookie = ProcessFunc.GetCookie(TicketDetailActivity.this);
		        	Result += updateTicket(TicketId,dtData,cookie.getUserId(), cookie.getCookie());
		        }
			} 
			catch (Exception e) {
				e.printStackTrace();
			}
			return Result;
		}
		
		@Override
		protected void onPostExecute(String result) {
			String sResponse[] = result.split("\\|");
			if (Integer.parseInt(sResponse[1]) == 0)
			{
				Button btUpdate = (Button)findViewById(Integer.parseInt(sResponse[0]));
				btUpdate.setEnabled(false);
			}
		    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(TicketDetailActivity.this);
            alertDialogBuilder.setTitle("Notice");
            alertDialogBuilder
            	.setMessage(sResponse[2].trim())
            	.setCancelable(false)
                .setPositiveButton("OK",
                		new DialogInterface.OnClickListener() {
                      		@Override
							public void onClick(DialogInterface dialog, int id) {
                                    	//TicketDetailActivity.this.finish();
                      		}
                    	});
            AlertDialog alertDialog = alertDialogBuilder.create();
            alertDialog.show();
		}
		
        @Override
        protected void onPreExecute() {
        	//CheckDataValid();
			//showProgress(true);
            //super.onPreExecute();
            //tv.setText("Started Running….");
        }
        
        @Override
        protected void onProgressUpdate(String... text) {
         //finalResult.setText(text[0]);
         // Things to be done while execution of long running operation is in
         // progress. For example updating ProgessDialog
        }
 	}

	
	private String GetTicket() {
    	InputStream is = null;
    	String result = "";
    	try{
    		HttpClient httpclient = new DefaultHttpClient();
    		HttpPost httppost = new HttpPost(Consts.MAIN_URL);
    		
    		CookieData cookie = ProcessFunc.GetCookie(TicketDetailActivity.this);
    		
    		List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(4);
            nameValuePair.add(new BasicNameValuePair(Consts.V_FUNC, Consts.F_TICKETDETAIL));
            nameValuePair.add(new BasicNameValuePair(Consts.V_TICKETID, String.valueOf(TicketId)));
            nameValuePair.add(new BasicNameValuePair(Consts.V_COOKIE,cookie.getCookie()));
            nameValuePair.add(new BasicNameValuePair(Consts.V_USERID,String.valueOf(cookie.getUserId())));
            
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePair));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
    		is = entity.getContent();
    	}
    	catch(Exception e){
    		Log.e("log_tag", "Error in http connection "+e.toString());
    	}

        try{
        	//BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
        	BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"),16);
	    	StringBuilder sb = new StringBuilder();
	    	String line = null;
	    	while ((line = reader.readLine()) != null) {
	    		sb.append(line + "\n");
	    	}
	    	is.close();
	    	result = sb.toString();
        }
		catch(Exception e){
	    	Log.e("test", "Error converting result "+e.toString());
	    }
        return result;
    }

	/**
	 * Set up the {@link android.app.ActionBar}, if the API is available.
	 */
	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	private void setupActionBar() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
			getActionBar().setDisplayHomeAsUpEnabled(true);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.atmsearch, menu);
        return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) 
	{
		if(item.getItemId() != R.id.menu_sub){
			startActivity(ProcessFunc.MenuAction(this, item));
		}
		
		return true;
	}

	private String updateTicket(int tTicketId, String tData, int tUserId, String tCookie)
	{
		InputStream is = null;
		String temp = "";
		try {
			
			HttpClient httpClient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(Consts.MAIN_URL);
	            
		    List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(5);
		    nameValuePair.add(new BasicNameValuePair(Consts.V_FUNC, Consts.F_UPDATETICKET));
		    nameValuePair.add(new BasicNameValuePair(Consts.V_USERID, String.valueOf(tUserId)));
		    nameValuePair.add(new BasicNameValuePair(Consts.V_COOKIE, tCookie));
		    nameValuePair.add(new BasicNameValuePair(Consts.V_TICKETID, String.valueOf(tTicketId)));
		    nameValuePair.add(new BasicNameValuePair(Consts.V_DATA, tData));
		            
		    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
		    HttpResponse response = httpClient.execute(httpPost);
		    HttpEntity entity = response.getEntity();
		    is = entity.getContent();
		    try{
		    	BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"),16);
			    StringBuilder sb = new StringBuilder();
			    String line = null;
			    while ((line = reader.readLine()) != null) {
			    	sb.append(line + "\n");
			    }
			    is.close();
			    temp = sb.toString();
			    	   	}
			catch(Exception e){
			   	Log.e("test", "Error converting result "+e.toString());
			}
		} 
		catch (ClientProtocolException  e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return temp;
	}

	/*@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
	private void showProgress(final boolean show) {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
			int shortAnimTime = getResources().getInteger(
					android.R.integer.config_shortAnimTime);

			mTicketDetailStatusView.setVisibility(View.VISIBLE);
			mTicketDetailStatusView.animate().setDuration(shortAnimTime)
					.alpha(show ? 1 : 0)
					.setListener(new AnimatorListenerAdapter() {
						@Override
						public void onAnimationEnd(Animator animation) {
							mTicketDetailStatusView.setVisibility(show ? View.VISIBLE
									: View.GONE);
						}
					});

			mTicketDetailFormView.setVisibility(View.VISIBLE);
			mTicketDetailFormView.animate().setDuration(shortAnimTime)
					.alpha(show ? 0 : 1)
					.setListener(new AnimatorListenerAdapter() {
						@Override
						public void onAnimationEnd(Animator animation) {
							mTicketDetailFormView.setVisibility(show ? View.GONE
									: View.VISIBLE);
						}
					});
		} else {
			// The ViewPropertyAnimator APIs are not available, so simply show
			// and hide the relevant UI components.
			mTicketDetailStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
			mTicketDetailFormView.setVisibility(show ? View.GONE : View.VISIBLE);
		}
	}*/
}
